package model

import (
	"os"
	"strconv"
	"gitee.com/liumou_site/logger"
)

// FlagConfig 存储所有配置参数
type FlagConfig struct {
	Urls      string
	ThreadNum int
	MaxSize   int64
	TimeStart int
	TimeStop  int
	Debug     bool
	Version   bool
	Memory    int64
}

// GetDefaultConfig 从环境变量获取默认配置
func GetDefaultConfig() *FlagConfig {
	config := &FlagConfig{
		Urls:      getEnvString("GOSPEED_URLS", "urls.txt"),
		ThreadNum: getEnvInt("GOSPEED_THREAD", 4),
		MaxSize:   getEnvInt64("GOSPEED_MAX_SIZE", 0),
		TimeStart: getEnvInt("GOSPEED_TIME_START", 9),
		TimeStop:  getEnvInt("GOSPEED_TIME_STOP", 23),
		Debug:     getEnvBool("GOSPEED_DEBUG", false),
		Version:   false,
		Memory:    getEnvInt64("GOSPEED_MEMORY", 2048),
	}

	// 添加环境变量读取日志
	if os.Getenv("GOSPEED_THREAD") != "" {
		logger.Info("环境变量 GOSPEED_THREAD=", config.ThreadNum)
	}
	if os.Getenv("GOSPEED_MAX_SIZE") != "" {
		logger.Info("环境变量 GOSPEED_MAX_SIZE=", config.MaxSize, " MB")
	}
	if os.Getenv("GOSPEED_TIME_START") != "" {
		logger.Info("环境变量 GOSPEED_TIME_START=", config.TimeStart)
	}
	if os.Getenv("GOSPEED_TIME_STOP") != "" {
		logger.Info("环境变量 GOSPEED_TIME_STOP=", config.TimeStop)
	}
	if os.Getenv("GOSPEED_URLS") != "" {
		logger.Info("环境变量 GOSPEED_URLS=", config.Urls)
	}
	if os.Getenv("GOSPEED_DEBUG") != "" {
		logger.Info("环境变量 GOSPEED_DEBUG=", config.Debug)
	}
	if os.Getenv("GOSPEED_MEMORY") != "" {
		logger.Info("环境变量 GOSPEED_MEMORY=", config.Memory, " MB")
	}

	return config
}

// getEnvString 从环境变量获取字符串值
func getEnvString(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// getEnvInt 从环境变量获取整数值
func getEnvInt(key string, defaultValue int) int {
	if value := os.Getenv(key); value != "" {
		if intValue, err := strconv.Atoi(value); err == nil {
			return intValue
		}
	}
	return defaultValue
}

// getEnvInt64 从环境变量获取int64值
func getEnvInt64(key string, defaultValue int64) int64 {
	if value := os.Getenv(key); value != "" {
		if intValue, err := strconv.ParseInt(value, 10, 64); err == nil {
			return intValue
		}
	}
	return defaultValue
}

// getEnvBool 从环境变量获取布尔值
func getEnvBool(key string, defaultValue bool) bool {
	if value := os.Getenv(key); value != "" {
		if boolValue, err := strconv.ParseBool(value); err == nil {
			return boolValue
		}
	}
	return defaultValue
}